package com.hanxiaozhang.config;

import com.hanxiaozhang.constant.RabbitConstant;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * 〈一句话功能简述〉<br>
 * 〈Topic交换机的Rabbit配置类〉
 *
 * @author hanxinghua
 * @create 2022/9/21
 * @since 1.0.0
 */
@Configuration
public class TopicRabbitConfig implements BeanPostProcessor {

    @Resource
    private RabbitAdmin rabbitAdmin;

    /**
     * 配置TopicExchange交换机
     *
     * @return
     */
    @Bean
    public TopicExchange rabbitTopicExchange() {

        return new TopicExchange(RabbitConstant.TOPIC_EXCHANGE, true, false);
    }

    /**
     * 创建队列A
     *
     * @return
     */
    @Bean
    public Queue topicExchangeQueueA() {

        return new Queue(RabbitConstant.TOPIC_QUEUE_A, true, false, false);
    }

    /**
     * 创建队列B
     *
     * @return
     */
    @Bean
    public Queue topicExchangeQueueB() {

        return new Queue(RabbitConstant.TOPIC_QUEUE_B, true, false, false);
    }

    /**
     * 创建队列C
     *
     * @return
     */
    @Bean
    public Queue topicExchangeQueueC() {

        return new Queue(RabbitConstant.TOPIC_QUEUE_C, true, false, false);
    }

    /**
     * 队列A绑定到FanoutExchange交换机
     *
     * @return
     */
    @Bean
    public Binding bindTopicA() {

        return BindingBuilder.bind(topicExchangeQueueA())
                .to(rabbitTopicExchange())
                .with("a.*");
    }

    /**
     * 队列B绑定到FanoutExchange交换机
     *
     * @return
     */
    @Bean
    public Binding bindTopicB() {

        return BindingBuilder.bind(topicExchangeQueueB())
                .to(rabbitTopicExchange())
                .with("a.#");
    }

    /**
     * 队列A绑定到FanoutExchange交换机
     *
     * @return
     */
    @Bean
    public Binding bindTopicC() {

        return BindingBuilder.bind(topicExchangeQueueC())
                .to(rabbitTopicExchange())
                .with("rabbit.#");
    }


    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        rabbitAdmin.declareExchange(rabbitTopicExchange());
        rabbitAdmin.declareQueue(topicExchangeQueueA());
        rabbitAdmin.declareQueue(topicExchangeQueueB());
        rabbitAdmin.declareQueue(topicExchangeQueueC());
        return null;
    }

}
